package com.driver.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.driver.mapper.TemperatureMapper;
import com.driver.pojo.entity.Temperature;
import com.driver.service.ITemperatureService;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;

@Service("temperatureService")
public class TemperatureServiceImpl extends ServiceImpl<TemperatureMapper, Temperature> implements ITemperatureService {

    @Override
    public byte[] generatePdf(List<Temperature> temperatures) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = new PdfWriter(baos);
        PdfDocument pdfDoc = new PdfDocument(writer);
        Document document = new Document(pdfDoc);

        Table table = new Table(UnitValue.createPercentArray(new float[]{1, 2, 2, 1}));
        table.addCell(new Cell().add(new Paragraph("ID")));
        table.addCell(new Cell().add(new Paragraph("Code")));
        table.addCell(new Cell().add(new Paragraph("Create Time")));
        table.addCell(new Cell().add(new Paragraph("Is Valid")));

        for (Temperature temp : temperatures) {
            table.addCell(new Cell().add(new Paragraph(String.valueOf(temp.getId()))));
            table.addCell(new Cell().add(new Paragraph(temp.getCode())));
            table.addCell(new Cell().add(new Paragraph(temp.getCreateTime().toString())));
            table.addCell(new Cell().add(new Paragraph(String.valueOf(temp.getIsValid()))));
        }

        document.add(table);
        document.close();

        return baos.toByteArray();
    }

}
